using System;
using System.Globalization;
using LambdaGp.Core;

namespace LambdaGp.Operators.Terminals
{
    public class Constant : Terminal
    {
        public Constant(double value)
            : base(value.ToString(CultureInfo.InvariantCulture))
        {
            Value = value;
        }
        
        public double Value { get; private set; }
        
        public override bool MatchesToken(string token, TokenPriority tokenPriority)
        {
            if (tokenPriority != TokenPriority.Primary)
            {
                return false;
            }

            token = token.Replace(",", ".");
            double value;

            if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
            {
                if (Math.Abs(value - Value) < 0.01)
                {
                    return true;
                }
            }

            return false;
        }
        
        public override Func<double> CompileToFunc(Individual individual, OperatorNode operatorNode)
        {
            return () => Value;
        }
    }
}
